import 'dart:convert';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:namewava/jc_tabbar.dart';
import 'package:namewava/utils/jc_cache.dart';
import 'package:namewava/utils/jc_global.dart';
import 'package:namewava/utils/jc_http_utils.dart';

class JsRequest {
  ///快速登录
  static appFastLogin({required Success success}) {
    var loginUrl = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveLogin;

    var configUrl = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveConfig;

    var appInfo = JcCache.getInstance().get('appinfo');
    Map info = jsonDecode(appInfo);

    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().getReques(
      configUrl,
      {'var': 0},
      isNeedToken: false,
      success: (data) {
        JcHttpUtils().postReques(
            loginUrl, {'token': info['device-id'], 'oauthType': 4},
            isNeedToken: false, success: (loginData) {
          EasyLoading.dismiss();
          success(loginData['data']);
        });
      },
    );
  }

  ///苹果登录
  static appleLogin({String? identityToken, required Success success}) {
    var loginUrl = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveLogin;

    var configUrl = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveConfig;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().getReques(
      configUrl,
      {'var': 0},
      isNeedToken: false,
      success: (data) {
        JcHttpUtils().postReques(
            loginUrl, {'token': identityToken, 'oauthType': 3},
            isNeedToken: false, success: (loginData) {
          EasyLoading.dismiss();
          success(loginData['data']);
        });
      },
    );
  }

  ///首页请求
  static homeRequest({required Success success}) {
    final waveValidToken = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveValidToken;

    final waveStrategy = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveStrategy;

    var wavaUserId = JcCache.getInstance().get('wavaUserId');
    var wavaToken = JcCache.getInstance().get('wavaToken');
    final waveUserInfo = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveUserInfo;

    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveValidToken, {'token': wavaToken},
        success: (tokenData) {
      JcHttpUtils().getReques(waveStrategy, <String, dynamic>{},
          success: (strategyData) {
        JcHttpUtils().getReques(waveUserInfo, {'userId': wavaUserId},
            success: (userInfo) {
          EasyLoading.dismiss();
          success(userInfo['data']);
        });
      });
    });
  }

  ////获取用户信息
  static getWavaUserInfo({required Success success}) {
    var wavaUserId = JcCache.getInstance().get('wavaUserId');
    final waveUserInfo = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveUserInfo;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().getReques(waveUserInfo, {'userId': wavaUserId},
        success: (userInfo) {
      EasyLoading.dismiss();
      success(userInfo['data']);
    });
  }

  /// 获取内购商品列表
  static getPurchaseList({required Success success}) {
    // var wavaUserId = JcCache.getInstance().get('wavaUserId');
    final waveGoods = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveGoods;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveGoods, {
      'isIncludeSubscription': false,
      'payChannel': 'IAP',
    }, success: (purchaseData) {
      EasyLoading.dismiss();
      success(purchaseData['data']);
    });
  }

  /// 创建内购订单
  static createRechargePurchase(
      {required String goodsCode, required Success success}) {
    // var wavaUserId = JcCache.getInstance().get('wavaUserId');
    final waveCreateRecharge =
        JcGlobal.of(navigatorKey.currentContext!).baseUrl +
            JcGlobal.of(navigatorKey.currentContext!).waveCreateRecharge;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveCreateRecharge, {
      'entry': '',
      'source': '',
      'goodsCode': goodsCode,
      'payChannel': 'IAP'
    }, success: (res) {
      EasyLoading.dismiss();
      success(res['data']);
    });
  }

  ///内购完成验单接口
  static rechargeCheck({required Map parms, required Success success}) {
    // var wavaUserId = JcCache.getInstance().get('wavaUserId');
    final waveRechargeCheck =
        JcGlobal.of(navigatorKey.currentContext!).baseUrl +
            JcGlobal.of(navigatorKey.currentContext!).waveRechargeCheck;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveRechargeCheck, parms, success: (res) {
      EasyLoading.dismiss();
      success(res['data']);
    });
  }

  ///消费内购币
  static costCoins({required Success success}) {
    final waveCoinsSpend = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveCoinsSpend;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveCoinsSpend, {
      'outlay': 10,
      'source': 'iap',
    }, success: (purchaseData) {
      EasyLoading.dismiss();
      success(purchaseData['data']);
    });
  }

  ///退出登录
  static logoutRequest({required Success success}) {
    final waveLogout = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveLogout;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveLogout, {}, success: (logoutData) {
      EasyLoading.dismiss();
      success(logoutData['data']);
    });
  }

  ///删除账号
  static deleteRequest({required Success success}) {
    final waveDeleteAccount =
        JcGlobal.of(navigatorKey.currentContext!).baseUrl +
            JcGlobal.of(navigatorKey.currentContext!).waveDeleteAccount;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveDeleteAccount, {}, success: (deleteData) {
      EasyLoading.dismiss();
      success(deleteData['data']);
    });
  }

  ///修改用户信息
  static fixUserInfoRequest({required Map parms, required Success success}) {
    final waveSaveUserInfo = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveSaveUserInfo;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(waveSaveUserInfo, parms, success: (userData) {
      EasyLoading.dismiss();
      success(userData['data']);
    });
  }

  ///获取上传附件所需的信息
  static getUpfileParms({required Success success}) {
    var wavePolicy = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).wavePolicy;
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().getReques(
      wavePolicy,
      <String, dynamic>{},
      success: (data) {
        EasyLoading.dismiss();
        success(data['data']);
      },
    );
  }

  ///修改用户头像
  static fixUserAvatarRequest(
      {required XFile file, required Map oss, required Success success}) async {
    var waveUpdateAvatar = JcGlobal.of(navigatorKey.currentContext!).baseUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveUpdateAvatar;

    ///file.path = /data/user/0/com.example.namewava/cache/df21e865-d3d5-4203-bd6d-9351ccae46846334739311239767342.jpg
    String fileName = file.path.split('/').last;
    String imageType = fileName.split('.').last;
    String imageName = '${randomImageName(20)}.$imageType';
    var filePath = await MultipartFile.fromFile(file.path, filename: fileName);
    final formData = FormData.fromMap({
      'policy': oss['policy'],
      'signature': oss['signature'],
      'ossaccessKeyId': oss['accessKeyId'],
      'key': '${oss['dir']}/$imageName',
      'callback': oss['callback'],
      'file': filePath,
    });
    EasyLoading.show(maskType: EasyLoadingMaskType.none);
    JcHttpUtils().postReques(oss['host'], formData, success: (fileData) {
      // print(fileData);
      // EasyLoading.dismiss();
      String filename = fileData['data']['filename'];

      JcHttpUtils().postReques(waveUpdateAvatar, {'avatarPath': filename},
          success: (res) {
        EasyLoading.dismiss();
        success(res['data']);
      });
    });
  }

  ///日志上报
  static wavaLogRequest({required Map p}) async {
    var waveLogUp = JcGlobal.of(navigatorKey.currentContext!).baseLogUrl +
        JcGlobal.of(navigatorKey.currentContext!).waveLogUp;
    JcHttpUtils().postLogReques(waveLogUp, p, success: (logData) {});
  }

  static randomImageName(int len) {
    // DateTime dateTime = DateTime.now();

    // int imageName = dateTime.millisecondsSinceEpoch +
    //     (dateTime.microsecondsSinceEpoch ~/ 1000000);
    // return imageName;
    final random = Random();
    const rondomStrs = 'qwertyuiopasdfghjklzxcvbnm';
    final resultStr = List.generate(len, (index) {
      return rondomStrs[random.nextInt(rondomStrs.length)];
    }).join();

    return resultStr;
  }
}
